package com.example.springmvcadv.config;

import com.example.springmvcadv.model.JsonResult;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

//统一响应数据格式：Controller返回对象，可以进一步封装
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice<Object> {
    //表示是否要进行封装
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    /**
     *
     * @param body Controller请求映射方法，返回值
     * @param returnType 可以通过这个对象获取Controller及方法
     * @return
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        JsonResult json = new JsonResult();
        json.setOk(true);
        json.setData(body);
        return json;
    }
}
